package com.class5.springboot.service.real;

import com.alibaba.fastjson.JSONObject;
import com.class5.springboot.config.Constants;
import com.class5.springboot.entity.TbXtFile;
import com.class5.springboot.frame.context.SuperServiceImpl;
import com.class5.springboot.service.facade.IUploadService;
import com.class5.springboot.util.FileHelper;
import com.class5.springboot.util.exception.ServiceException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@Service
public class UploadService extends SuperServiceImpl implements IUploadService{

    @Override
    public Long uploadFile(HttpServletRequest request){
        MultipartFile mfile = ((MultipartHttpServletRequest)request).getFile("file");
        JSONObject fileJson = FileHelper.MultipartFileToFile(mfile,Constants.FILE_TEST_URL);
        //保存到数据库
        TbXtFile tbXtFile = new TbXtFile();
        tbXtFile.setBizArgs("");
        tbXtFile.setBizId(Long.valueOf("11"));
        tbXtFile.setFileDesc("测试");
        tbXtFile.setFilePath(fileJson.getString("filePath"));
        tbXtFile.setFileTitle("文件标题");
        tbXtFile.setFileName(fileJson.getString("fileName"));
        tbXtFile.setFileSize(Long.valueOf(FileHelper.getFileLength(fileJson.getString("filePath"))));
        repo.insert(tbXtFile);
        return tbXtFile.getId();
    }


    @Override
    public TbXtFile getFileInfo(JSONObject param) {
        Long fileID = param.getLong("id");
        TbXtFile tbXtFile = repo.get(fileID,TbXtFile.class);
        if(tbXtFile == null){
            throw new ServiceException("文件不存在");
        }
        return tbXtFile;
    }


}
